package com.example.test.exception;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.example.test.util.ResultBean;
import com.example.test.util.StatusCode;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public ResultBean validExceptionHandler(BindException e){
        //e.printStackTrace();
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return ResultBean.error(StatusCode.FAIL.getCode(),msg);
    }

    @ExceptionHandler(DefinitionException.class)
    public ResultBean exceptionHandler(DefinitionException e){
        //e.printStackTrace();
        String msg = e.getMessage();
        return ResultBean.error(StatusCode.FAIL.getCode(), msg);
    }

    @ExceptionHandler(Exception.class)
    public ResultBean exceptionHandler(Exception e){
        //e.printStackTrace();
        String msg = e.getMessage();
        return ResultBean.error(StatusCode.SERVER_ERROR.getCode(), StatusCode.SERVER_ERROR.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBean handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
    {
        //log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return ResultBean.error(StatusCode.FAIL.getCode(),StatusCode.SERVER_ERROR.getMsg());
    }

    @ExceptionHandler(UnauthorizedException.class)
    public ResultBean UnauthorizedException(UnauthorizedException e)
    {
        return ResultBean.error(StatusCode.FAIL.getCode(),"无权限操作");
    }



}
